package com.xy.tianyu.network

import com.xy.tianyu.network.response.WallpaperResponse
import okhttp3.Response
import okio.IOException
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.entity.ParameterizedTypeImpl
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.AbstractParser
import rxhttp.wrapper.utils.convert
import java.lang.reflect.Type

/**
 * @time 2020/9/15 11:27
 * @class 描述:
 */
@Parser(name = "WallpaperResponse")
 open class WallpaperResponseParser<T> : AbstractParser<T> {
    //以下两个构造方法是必须的
    protected constructor() : super()
    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: Response): T {
        val type: Type = ParameterizedTypeImpl[WallpaperResponse::class.java, mType] //获取泛型类型
        val data: WallpaperResponse<T> = response.convert(type)   //获取Response对象
        val res = data.res                       //获取data字段
        if (data.code != 0 || res == null) { //code不等于0，说明数据不正确，抛出异常
            throw ParseException(data.code.toString(), data.msg, response)
        }
        return res

    }
}